#include "TCP.h"
#include<pthread.h>
void* thread_read(void *arg)
{
    pthread_t id=pthread_self();
    pthread_detach(id);

    char msg[1024];
    int cfd=*((int *)arg);
    while (1)
    {
        memset(msg,0,1024);
        read_noblock(cfd,msg,sizeof(msg));
        if(strlen(msg)>0)
        {
            send(cfd,msg,strlen(msg),MSG_NOSIGNAL);
            if(strcmp(msg,"quit\n")==0)
            {
                shutdown(cfd,SHUT_RDWR);
                pthread_exit(NULL);
            }
        }
    }
    
   
}
int main(int argc,char **argv)
{   
    int sockfd;
    int cfd;

    struct sockaddr_in c_addr;
    socklen_t c_size;
    sockfd=TCP_server_create();
    while(1)
    {
        c_size=sizeof(struct sockaddr_in);
        cfd=accept(sockfd,(struct sockaddr*)&c_addr,&c_size);
        if(cfd<0)
        {
           if(errno!=EAGAIN&&errno!=EWOULDBLOCK&&errno!=EINTR)
           { 
                perror("accpet error\n");
                exit(1);
            }
        }
        if(cfd > 0)
        {
            int temp=cfd;
            pthread_t p;
            pthread_create(&p,NULL,thread_read,(void *)&temp);
        }
    }

    return 0;
}